package cn.stronglink.assetmanage.business.sync;

import android.app.Dialog;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.net.HttpURLConnection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import cn.stronglink.assetmanage.BaseActivity;
import cn.stronglink.assetmanage.MyApplication;
import cn.stronglink.assetmanage.R;
import cn.stronglink.assetmanage.dao.AssetDao;
import cn.stronglink.assetmanage.dao.CheckDao;
import cn.stronglink.assetmanage.dao.DaoManager;
import cn.stronglink.assetmanage.dao.DaoSession;
import cn.stronglink.assetmanage.dao.InventoryDao;
import cn.stronglink.assetmanage.dao.InventoryDetailDao;
import cn.stronglink.assetmanage.dao.PatrolDao;
import cn.stronglink.assetmanage.dao.PatrolDetailDao;
import cn.stronglink.assetmanage.dao.RepailDetailDao;
import cn.stronglink.assetmanage.dao.RepairDao;
import cn.stronglink.assetmanage.dao.SearchAssetDao;
import cn.stronglink.assetmanage.dao.SyncContentDao;
import cn.stronglink.assetmanage.entity.Asset;
import cn.stronglink.assetmanage.entity.BaseData;
import cn.stronglink.assetmanage.entity.Brand;
import cn.stronglink.assetmanage.entity.Cabinet;
import cn.stronglink.assetmanage.entity.Check;
import cn.stronglink.assetmanage.entity.DataCenter;
import cn.stronglink.assetmanage.entity.Department;
import cn.stronglink.assetmanage.entity.Inventory;
import cn.stronglink.assetmanage.entity.InventoryDetail;
import cn.stronglink.assetmanage.entity.Model;
import cn.stronglink.assetmanage.entity.Patrol;
import cn.stronglink.assetmanage.entity.PatrolDetail;
import cn.stronglink.assetmanage.entity.RepailDetail;
import cn.stronglink.assetmanage.entity.Repair;
import cn.stronglink.assetmanage.entity.Result;
import cn.stronglink.assetmanage.entity.Room;
import cn.stronglink.assetmanage.entity.SearchAsset;
import cn.stronglink.assetmanage.entity.SyncContent;
import cn.stronglink.assetmanage.entity.Task;
import cn.stronglink.assetmanage.entity.Type;
import cn.stronglink.assetmanage.entity.User;
import cn.stronglink.assetmanage.utils.Constants;
import cn.stronglink.assetmanage.utils.ImageUtils;
import cn.stronglink.assetmanage.utils.ToastUtil;
import cn.stronglink.assetmanage.utils.dao.InventoryDataUtil;
import cn.stronglink.assetmanage.utils.dao.PatrolDataUtil;
import cn.stronglink.assetmanage.widget.CustomProgressDialog;
import cn.stronglink.netrequest.business.base.BaseDataService;
import cn.stronglink.netrequest.business.check.CheckService;
import cn.stronglink.netrequest.business.inventory.InventoryService;
import cn.stronglink.netrequest.business.patrol.PatrolService;
import cn.stronglink.netrequest.business.repail.RepairService;
import cn.stronglink.netrequest.business.search.SearchService;

public class OneKeySyncActivity extends BaseActivity implements View.OnClickListener {
    Dialog mDialog;
    Button btnSync;
    TextView txtShowSyncListener;
    BaseDataService baseDataService;
    CheckService checkService;
    SearchService searchService;
    List<SyncContent> list;
    StringBuffer sb = new StringBuffer();
    List<Repair> lsrepairList;
    private InventoryService inventoryService;
    private RepairService repairService;
    private PatrolService patrolService;
    private Gson gson = new Gson();
    private DaoSession session;
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss", Locale.getDefault());

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_one_key_sync);
        initViewAndData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        setSelectPosition(5);
    }

    private void initViewAndData() {
        initView();
        session = DaoManager.getDaoSession(MyApplication.APP_CONTEXT);
        baseDataService = new BaseDataService();
        checkService = new CheckService();
        inventoryService = new InventoryService();
        repairService = new RepairService();
        searchService = new SearchService();
        patrolService = new PatrolService();
        txtShowSyncListener.setMovementMethod(ScrollingMovementMethod.getInstance());
    }

    private void initView() {
        btnSync = findViewById(R.id.btnOneKeySync);
        txtShowSyncListener = findViewById(R.id.txtShowSyncListener);
        btnSync.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.btnOneKeySync:
                startSync();
                break;
            default:
                break;
        }
    }

    public void startSync() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mDialog = CustomProgressDialog.createLoadingDialog(OneKeySyncActivity.this, "数据同步中...");
                mDialog.setCancelable(false);
                mDialog.show();
            }
        });
        sb = new StringBuffer();
        list = DaoManager.getDaoSession(this).getSyncContentDao().queryBuilder().where(SyncContentDao.Properties.IsSelected.eq(true)).build().list();
        if (list.size() == 0) {
            ToastUtil.toastShort("请先设置需要同步的内容!");
            if (mDialog != null) {
                mDialog.cancel();
            }
            return;
        }
        if (null != btnSync) {
            btnSync.setClickable(false);
        }
        setTips(simpleDateFormat.format(new Date()) + "\t" + "准备同步数据!");
        try {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    for (int i = 0; i < list.size(); i++) {
                        int syncontent = list.get(i).getSyscType();
                        if (syncontent == 1) {
                            setTips(simpleDateFormat.format(new Date()) + "\t" + "开始同步基础数据!");
                            syncBaseDatas();
                            setTips(simpleDateFormat.format(new Date()) + "\t" + "开始同步资产数据!");
//                            updateAssetDatas();
                            downloadSearchAsset();

                        }
                        if (syncontent == 2) {
                            setTips(simpleDateFormat.format(new Date()) + "\t" + "开始同步入库数据!");
                            syncCheckDatas();
                        }
                        if (syncontent == 3) {
                            setTips(simpleDateFormat.format(new Date()) + "\t" + "开始同步盘点数据!");
                            syncInventDatas();
                        }
                        if (syncontent == 4) {
                            setTips(simpleDateFormat.format(new Date()) + "\t" + "开始同步巡检维修数据!");
                            syncPatralDatas();
                        }
                    }
                    if (mDialog != null) {
                        mDialog.cancel();
                    }
                    if (null != btnSync) {
                        btnSync.setClickable(true);
                        setTips(simpleDateFormat.format(new Date()) + "\t" + "同步完成!");
                    }
                }
            }).start();
        } catch (Exception ex) {
            ex.getLocalizedMessage();
        }
    }

    private void setTips(final String tips) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (null != sb && null != txtShowSyncListener) {
                    sb.append(tips).append("\n");
                    txtShowSyncListener.setText(sb.toString());
                }
            }
        });
    }

    private void syncCheckDatas() {
        List<Check> list = session.getCheckDao().queryBuilder().where(CheckDao.Properties.Status.eq(Constants.STATUS_FOUR)).build().list();
        try {
            uploadCheckList(list);
        } catch (Exception e) {
            setTips(simpleDateFormat.format(new Date()) + "\t" + "入库数据上传失败!");
            e.printStackTrace();
        }
        try {
            downloadCheckList();
        } catch (Exception e) {
            setTips(simpleDateFormat.format(new Date()) + "\t" + "入库数据下载失败!");
            e.printStackTrace();
        }
    }

    private void syncInventDatas() {
        List<Inventory> inventorieList = session.getInventoryDao().queryBuilder().where(InventoryDao.Properties.Status.eq(Constants.STATUS_ONE)).list();
        try {
            uploadInventoryList(inventorieList);
        } catch (Exception e) {
            setTips(simpleDateFormat.format(new Date()) + "\t" + "盘点数据上传失败!");
            e.printStackTrace();
        }
        try {
            downloadInventoryList();
        } catch (Exception e) {
            setTips(simpleDateFormat.format(new Date()) + "\t" + "盘点数据下载失败!");
            e.printStackTrace();
        }
    }

    private void syncPatralDatas() {
        List<Patrol> patrolList = session.getPatrolDao().queryBuilder().where(PatrolDao.Properties.Status.eq(Constants.STATUS_THREE)).list();
        lsrepairList = session.getRepairDao().queryBuilder().where(RepairDao.Properties.Status.eq(Constants.STATUS_THREE)).list();
        try {
            uploadPatrolList(patrolList);
        } catch (Exception e) {
            setTips(simpleDateFormat.format(new Date()) + "\t" + "巡检数据上传失败!");
            e.printStackTrace();
        }
        try {
            downloadPatrolList();
        } catch (Exception e) {
            setTips(simpleDateFormat.format(new Date()) + "\t" + "巡检数据下载失败!");
            e.printStackTrace();
        }
        try {
            uploadRepairList(lsrepairList);
        } catch (Exception e) {
            setTips(simpleDateFormat.format(new Date()) + "\t" + "维修数据上传失败!");
            e.printStackTrace();
        }
        try {
            downloadRepairList();
        } catch (Exception e) {
            setTips(simpleDateFormat.format(new Date()) + "\t" + "维修数据下载失败!");
            e.printStackTrace();
        }
    }

    private void syncBaseDatas() {
        try {
            String jsonResult = baseDataService.getBaseData();
            if ("".equals(jsonResult)) {
                setTips(simpleDateFormat.format(new Date()) + "\t" + "基础数据未更新!");
            }
            Result<BaseData> result = null;
            result = gson.fromJson(jsonResult, new TypeToken<Result<BaseData>>() {
            }.getType());
            if (result != null && result.getHttpCode() == HttpURLConnection.HTTP_OK) {
                if (result.getData() != null) {
                    saveBaseData(result.getData());
                }
                setTips(simpleDateFormat.format(new Date()) + "\t" + "基础数据更新成功!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            setTips(simpleDateFormat.format(new Date()) + "\t" + "基础数据更新失败!");
        }
    }

    private void updateAssetDatas() {
        List<SearchAsset> lsAsset = DaoManager.getDaoSession(this).getSearchAssetDao().queryBuilder().list();
        if (lsAsset.size() == 0) {
            //setTips("没有最近的资产更改!");
            return;
        }
        try {
            for (SearchAsset searchAsset : lsAsset) {
                String uploadResult = gson.toJson(searchAsset);
                String jsonResult = searchService.updateAssetData(uploadResult);
                if ("".equals(jsonResult)) {
                    setTips(simpleDateFormat.format(new Date()) + "\t" + "资产数据未上传!");
                } else {
                    Result<String> result = null;
                    result = gson.fromJson(jsonResult, new TypeToken<Result<String>>() {
                    }.getType());
                    if (result != null && result.getHttpCode() == 200) {
                    } else {
                        setTips(simpleDateFormat.format(new Date()) + "\t" + "资产数据" + "上传失败!" + result.getMsg());
                        return;
                    }
                }
            }
            setTips(simpleDateFormat.format(new Date()) + "\t" + "资产数据" + "上传成功!");
            //删除本地相关图片
        } catch (Exception e) {
            e.printStackTrace();
            setTips(simpleDateFormat.format(new Date()) + "\t" + "资产数据上传失败!");
        }
    }

    private void downloadSearchAsset() {
        try {
            String jsonResult = searchService.downloadAssetData();
            Result<List<SearchAsset>> searchResult = null;
            searchResult = gson.fromJson(jsonResult, new TypeToken<Result<List<SearchAsset>>>() {
            }.getType());
            DaoManager.getDaoSession(this).getSearchAssetDao().deleteAll();
            List<SearchAsset> lsSearch = searchResult.getData();
            for (SearchAsset asset : lsSearch) {
                if (asset.getImgPath() != null && !asset.getImgPath().isEmpty()) {
                    String url = ImageUtils.base64ToFile(asset.getImgPath());
                    if (url != null) {
                        asset.setPictureUri(url);
                    }
                }
                DaoManager.getDaoSession(this).getSearchAssetDao().insertOrReplace(asset);
            }
            setTips(simpleDateFormat.format(new Date()) + "\t" + "资产数据同步成功!");
        } catch (Exception e) {
            e.printStackTrace();
            setTips(simpleDateFormat.format(new Date()) + "\t" + "资产数据未更新!");
        }
    }

    private void uploadCheckList(List<Check> checkList) throws Exception {
        if (checkList != null && checkList.size() > 0) {
            for (Check check : checkList) {
                check.setId(Long.valueOf(check.getId_()));
                List<Asset> assetList = session.getAssetDao().queryBuilder().where(AssetDao.Properties.OrderNo.eq(check.getId_())).list();
                if (assetList != null && assetList.size() > 0) {
                    for (Asset asset : assetList) {
                        if (null != asset.getId_() && !asset.getId_().equals("")) {
                            asset.setId(Long.valueOf(asset.getId_()));
                        }
                        if (asset.getBrandId_() != null && !asset.getBrandId_().equals("")) {
                            asset.setBrandId(Long.valueOf(asset.getBrandId_()));
                        }
                        if (asset.getModelId_() != null && !asset.getModelId_().equals("") ) {
                            asset.setModelId(Long.valueOf(asset.getModelId_()));
                        }
                        if (asset.getTypeId_() != null && !asset.getTypeId_().equals("")) {
                            asset.setTypeId(Long.valueOf(asset.getTypeId_()));
                        }
                        if (asset.getDatacenterId_() != null && !asset.getDatacenterId_().equals("")) {
                            asset.setDatacenterId(Long.valueOf(asset.getDatacenterId_()));
                        }
                        if (asset.getRoomId_() != null && !asset.getRoomId_().equals("")) {
                            asset.setRoomId(Long.valueOf(asset.getRoomId_()));
                        }
//                        if (asset.getPictureUri() != null && !"".equals(asset.getPictureUri())) {
//                            String imgPath = ImageUtils.imageToBase64(asset.getPictureUri());
//                            asset.setImgPath(imgPath);
//                        }
                    }
                    check.setAssetList(assetList);
                }
                if (!uploadCheck(check)) {
                    return;
                }
            }
        }
    }

    private boolean downloadCheckList() {
        try {
            String json = checkService.downloadPresetWorkOrder(User.getInstance().getId_());
            return !"".equals(json) && saveCheckData(json);
        } catch (Exception e) {
            setTips(simpleDateFormat.format(new Date()) + "\t" + "下载入库数据失败!");
            return false;
        }
    }

    private void uploadInventoryList(List<Inventory> inventorieList) throws Exception {
        if (inventorieList != null && inventorieList.size() > 0) {
            for (Inventory inventory : inventorieList) {
                inventory.setId(Long.valueOf(inventory.getId_()));
                String userId = User.getInstance().getId_();
                if (userId != null && !"".equals(userId)) {
                    inventory.setUpdateBy(Long.valueOf(userId));
                }
                // 正常盘点列表
                List<InventoryDetail> inventoryDetailList = session.getInventoryDetailDao().queryBuilder()
                        .where(InventoryDetailDao.Properties.OrderNo.eq(inventory.getId_()), InventoryDetailDao.Properties.Status.notEq(Constants.STATUS_FIVE)).list();
                if (inventoryDetailList != null && inventoryDetailList.size() > 0) {
                    for (InventoryDetail detail : inventoryDetailList) {
                        detail.setId(Long.valueOf(detail.getId_()));
                        if (detail.getBrandId_() != null) {
                            detail.setBrandId(Long.valueOf(detail.getBrandId_()));
                        }
                        if (detail.getModelId_() != null) {
                            detail.setModelId(Long.valueOf(detail.getModelId_()));
                        }
                        if (detail.getTypeId_() != null) {
                            detail.setTypeId(Long.valueOf(detail.getTypeId_()));
                        }
                        if (detail.getDatacenterId_() != null) {
                            detail.setDatacenterId(Long.valueOf(detail.getDatacenterId_()));
                        }
                        if (detail.getRoomId_() != null) {
                            detail.setRoomId(Long.valueOf(detail.getRoomId_()));
                        }
                    }
                    for (int j = 0; j < inventoryDetailList.size(); j++) {
                        InventoryDetail inventoryDetail = inventoryDetailList.get(j);
                        inventoryDetail.setId(Long.valueOf(inventoryDetail.getId_()));
                    }
                    inventory.setDetailList(inventoryDetailList);
                }
                // 盘盈列表
                List<InventoryDetail> moreOutList = session.getInventoryDetailDao().queryBuilder()
                        .where(InventoryDetailDao.Properties.OrderNo.eq(inventory.getId_()),
                                InventoryDetailDao.Properties.Status.eq(Constants.STATUS_FIVE)).list();
                if (null != moreOutList && moreOutList.size() > 0) {
                    inventory.setMoreOutList(moreOutList);
                }
                if (!uploadInventory(inventory)) {
                    return;
                }
            }
        }
    }

    private void downloadInventoryList() throws Exception {
        String result = inventoryService.downloadInventoryWorkOrder(User.getInstance().getId_());
        if ("".equals(result)) {
            setTips(simpleDateFormat.format(new Date()) + "\t" + "盘点数据下载失败!");
            return;
        }
        saveInventoryData(result);
    }

    private void uploadPatrolList(List<Patrol> patrolList) {
        if (patrolList != null && patrolList.size() > 0) {
            for (Patrol patrol : patrolList) {
                patrol.setId(Long.valueOf(patrol.getId_()));
                List<PatrolDetail> patrolDetailList = session.getPatrolDetailDao().queryBuilder()
                        .where(PatrolDetailDao.Properties.OrderNo.eq(patrol.getId_())).list();
                if (patrolDetailList != null && patrolDetailList.size() > 0) {
                    for (PatrolDetail detail : patrolDetailList) {
                        detail.setId(Long.valueOf(detail.getId_()));
                        if (detail.getBrandId_() != null && !detail.getBrandId_().equals("")) {
                            detail.setBrandId(Long.valueOf(detail.getBrandId_()));
                        }
                        if (detail.getModelId_() != null && !detail.getModelId_().equals("")) {
                            detail.setModelId(Long.valueOf(detail.getModelId_()));
                        }
                        if (detail.getTypeId_() != null&&!detail.getTypeId_().equals("")) {
                            detail.setTypeId(Long.valueOf(detail.getTypeId_()));
                        }
                        if (detail.getDatacenterId_() != null&&!detail.getDatacenterId_().equals("")) {
                            detail.setDatacenterId(Long.valueOf(detail.getDatacenterId_()));
                        }
                        if (detail.getManageBranchId_() != null && !detail.getManageBranchId_().equals("") ) {
                            detail.setManageBranchId(Long.valueOf(detail.getManageBranchId_()));
                        }
                        if (detail.getRoomId_() != null && !detail.getRoomId_().equals("")) {
                            detail.setRoomId(Long.valueOf(detail.getRoomId_()));
                        }
                        if (detail.getUseBranchId_() != null && !detail.getUseBranchId_().equals("")) {
                            detail.setUseBranchId(Long.valueOf(detail.getUseBranchId_()));
                        }
                    }
                    patrol.setDetailList(patrolDetailList);
                    patrol.setStatus(Constants.STATUS_THREE);
                }
                if (!uploadPatrol(patrol)) {
                    return;
                }
            }
        }

    }

    private void downloadPatrolList() {
        try {
            String jsonResult = patrolService.downloadPatrolWorkOrder(User.getInstance().getId_());
            if ("".equals(jsonResult)) {
                setTips(simpleDateFormat.format(new Date()) + "\t" + "巡检数据下载失败!");
                return;
            }
            savePatrolData(jsonResult);
        } catch (Exception e) {
            e.printStackTrace();
            setTips(simpleDateFormat.format(new Date()) + "\t" + "巡检数据下载失败!");
        }
    }

    private void uploadRepairList(List<Repair> repairList) {
        if (repairList != null && repairList.size() > 0) {
            for (Repair repair : repairList) {
                repair.setId(Long.valueOf(repair.getId_()));
                List<RepailDetail> repailDetailList = session.getRepailDetailDao().queryBuilder()
                        .where(RepailDetailDao.Properties.RepairId_.eq(repair.getId_())).list();
                if (repailDetailList != null && repailDetailList.size() > 0) {
                    for (RepailDetail detail : repailDetailList) {
                        detail.setId(Long.valueOf(detail.getId_()));
                        detail.setRepairId(Long.valueOf(detail.getRepairId_()));
                    }
                    repair.setDetailList(repailDetailList);
                }
                if (!uploadRepair(repair)) {
                    return;
                }
            }
        }
    }

    private void downloadRepairList() {
        try {
            String reult = repairService.downloadRepairWorkOrder(User.getInstance().getId_());
            if ("".equals(reult)) {
                setTips(simpleDateFormat.format(new Date()) + "\t" + "维修数据下载失败!");
                return;
            }
            saveRepairData(reult);
        } catch (Exception e) {
            e.printStackTrace();
            setTips(simpleDateFormat.format(new Date()) + "\t" + "维修数据下载失败!");
        }
    }

    private void saveBaseData(BaseData baseData) {
        if (baseData == null) {
            return;
        }
        DaoSession session = DaoManager.getDaoSession(this);

        // 数据中心
        List<DataCenter> dataCenterList = baseData.getDataCenterList();
        if (dataCenterList != null && dataCenterList.size() > 0) {
            session.getDataCenterDao().deleteAll();
            for (DataCenter dataCenter : dataCenterList) {
                session.getDataCenterDao().insert(dataCenter);
            }
        }

        // 地点
        List<Room> roomList = baseData.getRoomList();
        if (roomList != null && roomList.size() > 0) {
            session.getRoomDao().deleteAll();
            for (Room room : roomList) {
                session.getRoomDao().insert(room);
            }
        }

        // 品牌
        List<Brand> brandList = baseData.getBrandList();
        if (brandList != null && brandList.size() > 0) {
            session.getBrandDao().deleteAll();
            for (Brand brand : brandList) {
                session.getBrandDao().insert(brand);
            }
        }

        // 类型
        List<Type> typeList = baseData.getTypeVo();
        if (typeList != null && typeList.size() > 0) {
            session.getTypeDao().deleteAll();
            for (Type type : typeList) {
                session.getTypeDao().insert(type);
            }
        }

        // 型号
        List<Model> modelList = baseData.getModelList();
        if (modelList != null && modelList.size() > 0) {
            session.getModelDao().deleteAll();
            for (Model model : modelList) {
                session.getModelDao().insert(model);
            }
        }

        // 部门
        List<Department> departmentList = baseData.getDepartmentList();
        if (departmentList != null && departmentList.size() > 0) {
            session.getDepartmentDao().deleteAll();
            for (Department department : departmentList) {
                session.getDepartmentDao().insert(department);
            }
        }

        // 用户
        List<User> userList = baseData.getUserList();
        if (userList != null && userList.size() > 0) {
            session.getUserDao().deleteAll();
            for (User user : userList) {
                session.getUserDao().insert(user);
            }
        }

        //机柜
        List<Cabinet> cabinetList = baseData.getCabinetList();
        if (cabinetList != null && cabinetList.size() > 0) {
            session.getCabinetDao().deleteAll();
            session.getCabinetDao().insertInTx(cabinetList);
        }
    }

    private boolean uploadCheck(final Check check) {
        String json = gson.toJson(check);
        if ("".equals(json)) {
            setTips(simpleDateFormat.format(new Date()) + "\t" + "入库数据上传失败!");
            return false;
        }
        try {
            Result<String> result = null;
            String sucessJson = checkService.uploadCheckList(json);
            result = gson.fromJson(sucessJson, new TypeToken<Result<String>>() {
            }.getType());
            if (result != null && result.getHttpCode() == 200) {
                session.getCheckDao().deleteByKey(check.getCheck_id());
                session.getAssetDao().deleteInTx(check.getAssetList());
                for (Asset asset : check.getAssetList()) {
                    if (asset.getPictureUri() != null) {
                        ImageUtils.deleteImage(asset.getPictureUri());
                    }
                }
                setTips(simpleDateFormat.format(new Date()) + "\t" + "验收单" + check.getCheck_id() + "上传成功!");
                return true;
            } else {
                setTips(simpleDateFormat.format(new Date()) + "\t" + "验收单" + check.getCheck_id() + "上传失败!");
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            setTips(simpleDateFormat.format(new Date()) + "\t" + "入库数据上传失败!");
            return false;
        }
    }

    private boolean saveCheckData(String requestJson) {
        Result<List<Check>> checkResult = null;
        List<String> lsId = new ArrayList<>();
        List<Check> lsOldChek = session.getCheckDao().queryBuilder().build().list();
        for (int i = 0; i < lsOldChek.size(); i++) {
            lsId.add(lsOldChek.get(i).getId_());
        }
        checkResult = gson.fromJson(requestJson, new TypeToken<Result<List<Check>>>() {
        }.getType());
        if (checkResult != null && checkResult.getHttpCode() == HttpURLConnection.HTTP_OK) {
            if (checkResult.getData() != null) {
                List<Check> checkList = checkResult.getData();
                // 验收单列表
                if (checkList != null && checkList.size() > 0) {
                    //从服务器获取入库验收数据，成功后，清除本地入库验收数据库表
                    for (Check check : checkList) {
                        if (lsId.contains(check.getId_())) {
                            continue;
                        }
                        check.setOrderType(Constants.STATUS_ONE);
                        DaoManager.getDaoSession(MyApplication.APP_CONTEXT).getCheckDao().insert(check);
                        // 获取详情
                        if (check.getAssetList() != null && check.getAssetList().size() > 0) {
                            for (Asset asset : check.getAssetList()) {
                                asset.setOrderNo(check.getId_());
                                String base64Str = asset.getImgPath();
                                if (null != base64Str) {
                                    String pictureUrl = ImageUtils.base64ToFile(base64Str);
                                    if (pictureUrl != null && !"".equals(pictureUrl)) {
                                        asset.setPictureUri(pictureUrl);
                                        asset.setImgPath(ImageUtils.imageToBase64(pictureUrl));
                                    }
                                }
                                DaoManager.getDaoSession(MyApplication.APP_CONTEXT).getAssetDao().insert(asset);
                            }
                        }
                    }
                }
            }
            setTips(simpleDateFormat.format(new Date()) + "\t" + "入库数据下载成功!");
            return true;
        }
        setTips(simpleDateFormat.format(new Date()) + "\t" + "入库数据下载失败!");
        return false;
    }

    private boolean uploadInventory(final Inventory inventory) {
        String json = gson.toJson(inventory);
        try {
            String resultJson = inventoryService.uploadInventoryList(json);
            if ("".equals(resultJson)) {
                setTips(simpleDateFormat.format(new Date()) + "\t" + "盘点数据上传失败!");
                return false;
            }
            Result<String> result = null;
            result = gson.fromJson(resultJson, new TypeToken<Result<String>>() {
            }.getType());
            if (result != null && result.getHttpCode() == 200) {
                session.getInventoryDao().deleteByKey(inventory.getInventory_id());
                session.getInventoryDetailDao().deleteInTx(inventory.getDetailList());
                setTips(simpleDateFormat.format(new Date()) + "\t" + "盘点单" + inventory.getInventory_id() + "上传成功!");
                return true;
            } else {
                setTips(simpleDateFormat.format(new Date()) + "\t" + "盘点单" + inventory.getInventory_id() + "上传失败!");
            }
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            setTips(simpleDateFormat.format(new Date()) + "\t" + "盘点数据上传失败!");
            return false;
        }
    }

    private void saveInventoryData(String resultJson) {
        Result<List<Inventory>> inventoryResult = null;
        inventoryResult = gson.fromJson(resultJson, new TypeToken<Result<List<Inventory>>>() {
        }.getType());
        if (inventoryResult != null && inventoryResult.getHttpCode() == HttpURLConnection.HTTP_OK) {
            if (inventoryResult.getData() != null) {
                List<Inventory> inventoryList = inventoryResult.getData();
                // 验收单列表
                if (inventoryList != null && inventoryList.size() > 0) {
                    //从服务器获取盘点数据，清除本地盘点数据库表
                    for (Inventory inventory : inventoryList) {
                        // 如果盘点单存在，就不添加
                        Inventory tempInventory = DaoManager.getDaoSession(MyApplication.APP_CONTEXT).getInventoryDao().queryBuilder().where(
                                InventoryDao.Properties.Id_.eq(inventory.getId_())
                        ).unique();
                        if (tempInventory != null) {
                            continue;
                        }
                        inventory.setOrderType(Constants.STATUS_TWO);
                        inventory.setStatus(0);
                        DaoManager.getDaoSession(MyApplication.APP_CONTEXT).getInventoryDao().insertOrReplace(inventory);
                        InventoryDataUtil.saveInventoryDetailList(inventory.getDetailList(), inventory);
                        InventoryDataUtil.saveInventoryDetailList(inventory.getMoreOutList(), inventory);
                    }
                }
            }
            setTips(simpleDateFormat.format(new Date()) + "\t" + "盘点数据下载成功!");
            return;
        }
        setTips(simpleDateFormat.format(new Date()) + "\t" + "盘点数据下载失败!");
    }

    public boolean uploadPatrol(final Patrol patrol) {
        String json = gson.toJson(patrol);
        try {
            String jsonResult = patrolService.uploadPatrolWorkOrder(json);
            if ("".equals(jsonResult)) {
                setTips(simpleDateFormat.format(new Date()) + "\t" + "巡检数据上传失败!");
                return false;
            }
            Result<String> result = null;
            result = gson.fromJson(jsonResult, new TypeToken<Result<String>>() {
            }.getType());
            if (result != null && result.getHttpCode() == 200) {
                session.getPatrolDao().deleteByKey(patrol.getPatrol_id());
                session.getPatrolDetailDao().deleteInTx(patrol.getDetailList());
                setTips(simpleDateFormat.format(new Date()) + "\t" + "巡检单" + patrol.getPatrol_id() + "上传成功!");
                return true;
            } else {
                setTips(simpleDateFormat.format(new Date()) + "\t" + "巡检单" + patrol.getPatrol_id() + "上传失败!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            setTips(simpleDateFormat.format(new Date()) + "\t" + "巡检数据上传失败!");
        }
        return false;
    }

    private void savePatrolData(String resultJson) {
        Result<List<Patrol>> repairResult = null;
        List<String> lsId = new ArrayList<>();
        List<Patrol> lsOldPatrol = session.getPatrolDao().queryBuilder().build().list();
        for (int i = 0; i < lsOldPatrol.size(); i++) {
            lsId.add(lsOldPatrol.get(i).getId_());
        }
        repairResult = gson.fromJson(resultJson, new TypeToken<Result<List<Patrol>>>() {
        }.getType());
        if (repairResult != null && repairResult.getHttpCode() == HttpURLConnection.HTTP_OK) {
            if (repairResult.getData() != null) {
                List<Patrol> inventoryList = repairResult.getData();
                // 验收单列表
                if (inventoryList != null && inventoryList.size() > 0) {
                    for (Patrol patrol : inventoryList) {
                        if (lsId.contains(patrol.getId_())) {
                            continue;
                        }
                        patrol.setOrderType(Constants.STATUS_THREE);
                        //将巡检单列表保存在任务表中
                        Task task = new Task();
                        task.setId(patrol.getId());
                        task.setId_(patrol.getId_());
                        task.setStatus(patrol.getStatus());
                        task.setBusinessType(Constants.STATUS_THREE);
                        DaoManager.getDaoSession(MyApplication.APP_CONTEXT).getTaskDao().insertOrReplace(task);
                        DaoManager.getDaoSession(MyApplication.APP_CONTEXT).getPatrolDao().insert(patrol);
                        // 将SearchAsset数据保存到PatrolDetail里面
                        List<SearchAsset> searchAssetList = PatrolDataUtil.getSearchAssetByRoomId(patrol.getRoomId_());
                        PatrolDataUtil.savePatrolDetailData(patrol, searchAssetList, true);
                    }
                }
            }
            setTips(simpleDateFormat.format(new Date()) + "\t" + "巡检数据下载成功!");
            return;
        }
        setTips(simpleDateFormat.format(new Date()) + "\t" + "巡检数据下载失败!");
    }

    private boolean uploadRepair(final Repair repair) {
        String json = gson.toJson(repair);
        try {
            String jsonResult = repairService.uploadRepairWorkOrder(json);
            if ("".equals(jsonResult)) {
                setTips(simpleDateFormat.format(new Date()) + "\t" + "维修数据上传失败!");
                return false;
            }
            Result<String> result = null;
            result = gson.fromJson(jsonResult, new TypeToken<Result<String>>() {
            }.getType());
            if (result != null && result.getHttpCode() == 200) {
                session.getRepairDao().deleteByKey(repair.getRepair_id());
                session.getRepailDetailDao().deleteInTx(repair.getDetailList());
                setTips(simpleDateFormat.format(new Date()) + "\t" + "维修单" + repair.getRepair_id() + "上传成功!");
                return true;
            } else {
                setTips(simpleDateFormat.format(new Date()) + "\t" + "维修单" + repair.getRepair_id() + "上传失败!");
            }
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            setTips(simpleDateFormat.format(new Date()) + "\t" + "维修数据上传失败!");
        }
        return false;
    }

    private void saveRepairData(String requestJson) {
        Result<List<Repair>> repairResult = null;
        List<String> lsId = new ArrayList<>();
        List<Repair> lsOldPatrol = session.getRepairDao().queryBuilder().build().list();
        for (int i = 0; i < lsOldPatrol.size(); i++) {
            lsId.add(lsOldPatrol.get(i).getId_());
        }
        repairResult = gson.fromJson(requestJson, new TypeToken<Result<List<Repair>>>() {
        }.getType());
        if (repairResult != null && repairResult.getHttpCode() == HttpURLConnection.HTTP_OK) {
            if (repairResult.getData() != null) {
                List<Repair> repairList = repairResult.getData();
                // 验收单列表
                if (repairList != null && repairList.size() > 0) {
                    //从服务器获取维修单数据，成功后，清除本地维修单数据库表
                    for (Repair repair : repairList) {
                        if (lsId.contains(repair.getId_())) {
                            continue;
                        }
                        repair.setOrderType(Constants.STATUS_FOUR);
                        DaoManager.getDaoSession(MyApplication.APP_CONTEXT).getRepairDao().insert(repair);
                        //将验收单列表保存在任务表中
                        Task task = new Task();
                        task.setId(repair.getId());
                        task.setId_(repair.getId_());
                        task.setStatus(repair.getStatus());
                        task.setBusinessType(Constants.STATUS_FOUR);
                        task.setCreateTime(repair.getCreateTime());
                        task.setCreateUser(repair.getCreateName());
                        task.setExecuteTime(repair.getExecuteTime());
                        DaoManager.getDaoSession(MyApplication.APP_CONTEXT).getTaskDao().insertOrReplace(task);
                        // 获取详情
                        if (repair.getDetailList() != null && repair.getDetailList().size() > 0) {
                            for (RepailDetail repailDetail : repair.getDetailList()) {
                                repailDetail.setRepairId_(repair.getId_());
                                DaoManager.getDaoSession(MyApplication.APP_CONTEXT).getRepailDetailDao().insert(repailDetail);
                            }
                        }
                    }
                }
            }
            setTips(simpleDateFormat.format(new Date()) + "\t" + "维修数据下载成功!");
            return;
        }
        setTips(simpleDateFormat.format(new Date()) + "\t" + "维修数据下载失败!");
    }

    @Override
    public void onBackPressed() {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mDialog != null) {
            mDialog.cancel();
        }
    }
}
